/*
 * System : Ticketing
 * Package: com.ql2.ticketing.dao
 * Class: LoginService
 *
 * © QL2 Software 2011
 */
package main.java.org.dss.lm.admin.dao.login;

import com.lm.ledger.exception.LedgerException;
import com.lm.ledger.service.TransactionService;
import com.lm.ledger.service.TransactionServiceImp;
import com.lm.ledger.utill.Group;
import com.lm.ledger.utill.Location;
import com.lm.ledger.utill.User;
import com.opensymphony.xwork2.ActionContext;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;



import main.java.org.dss.lm.admin.bean.LoginBean;
import main.java.org.dss.lm.admin.bean.RoleBean;
import main.java.org.dss.lm.admin.bean.UserBean;
import main.java.org.dss.lm.admin.common.ITSConstants;
import main.java.org.dss.lm.admin.connection.DatabaseConnection;
import main.java.org.dss.lm.admin.util.LocMgmtUtil;

/**
 * This class implements {@link com.ql2.ticketing.dao.ILoginService} interface and performs login authentication from the
 * database.
 */
public class LoginService implements ILoginService {
	
	DatabaseConnection lmDB = new DatabaseConnection();
    Connection con;
    PreparedStatement pst1 = null;
    ResultSet rs1 = null;  
    PreparedStatement pst2 = null;
    ResultSet rs2 = null;
   
	/**
     * This method checks for the user whether authorized/unauthorized to login during the login
     * process.
     *
     * @param accountEntity the AccountEntity object.
     * @return String value indicating success or failure during the authentication.
     */
    @Override
    public String checkAuthentication(LoginBean loginBean) 
    { System.out.println("test1");
    	try {
        	con=lmDB.getDBConnection();
        	pst1 = con.prepareStatement("select JameInsanID, InsanID, Name, Adress, Block, District, State, Country, ContactNumber, RoleID from user WHERE InsanID = ? and Password = ? and Status = ?");
            pst1.setString(1, loginBean.getFrm_username());
            pst1.setString(2, loginBean.getFrm_password());
            pst1.setString(3, ITSConstants.ACTIVE);
            rs1 = pst1.executeQuery();
            System.out.println("test2");
            if(rs1.next()){
            	System.out.println("test3");
            	UserBean userBean = new UserBean();            	
            	userBean.setJiid(rs1.getString("JameInsanID"));
            	userBean.setInsanId(rs1.getString("InsanID"));
            	userBean.setName(rs1.getString("Name"));
            	userBean.setAddress(rs1.getString("Adress"));
            	userBean.setBlock(rs1.getString("Block"));
            	userBean.setDistrict(rs1.getString("District"));
            	userBean.setState(rs1.getString("State"));
            	userBean.setCountry(rs1.getString("Country"));
            	userBean.setContactNumber(rs1.getString("ContactNumber"));
            	userBean.setRole(rs1.getString("RoleID"));           	
            	System.out.println("debug---1");
            	ActionContext.getContext().getSession().put(ITSConstants.CURRENT_USER_DETAILS, userBean);
            	setUserInSession(loginBean.getFrm_username());
            	setUserGroupsInSession();
            	System.out.println(rs1.getString("RoleID"));
            	if(ITSConstants.ADMIN_ROLE.equals(rs1.getString("RoleID"))){         		
            	
            		List<RoleBean> roleList = new ArrayList<RoleBean>();
            		RoleBean roleBean;
            		
            		pst2 = con.prepareStatement("select RoleID, RoleDescription from role order by RoleID ");                    
                    rs2 = pst2.executeQuery();
                    while(rs2.next()){
                    	roleBean = new RoleBean();
                    	roleBean.setRoleId(rs2.getString("RoleID"));
                    	roleBean.setRoleDescription(rs2.getString("RoleDescription"));                    	
                    	roleList.add(roleBean);
                    }                    
                    System.out.println("role list size  "+roleList.size());
                    ActionContext.getContext().getSession().put(ITSConstants.ROLE_LIST, roleList);
            	}            	
                return ITSConstants.AUTHORIZED;
            }            
        } 
        catch(Exception e){e.printStackTrace();}
        finally{try{if(pst1!=null)pst1.close();if(rs1!=null)rs1.close();if(pst2!=null)pst2.close();if(rs2!=null)rs2.close();if(con!=null)con.close();}catch(SQLException ee){}}
        return ITSConstants.UNAUTHORIZED;
    } 
    
    public void setUserInSession(String id){
    	System.out.println("setUserInSession debug 1.........");
    	TransactionService service = new TransactionServiceImp();
        ActionContext  context = ActionContext.getContext();
		Map session = context.getSession();
    	User user = service.userDetail(id);
    	System.out.println("setUserInSession debug 2.........");
    	if(user!=null){
    		session.put("USER", user);
    		String name = user.getName();
        	String pwd = user.getPwd();
        	String insanId = user.getInsanNo();
        	System.out.println("setUserInSession debug 3.........");
        	String role = user.getRoleName();  
        	System.out.println("name ***=== "+name);
    		System.out.println("role ===*** "+role);
    		List<Location> locList = null;
			
				locList = service.getLocations(user.getUserId());
			
    		System.out.println("locList %%%%%%%%%%%%%% "+locList);
    		session.put("LOCLIST", locList);
    		System.out.println("setUserInSession debug 4.........");
    		if(role!=null){
    			System.out.println("role is not null");
    			session.put("USERROLE", role);
    		}else{
    			System.out.println("role is null");
    		}	
    	}
    }
    
    private void setUserGroupsInSession(){
    	System.out.println("setUserGroupsInSession debug 1.........");
    	List<Group> groups = new ArrayList<Group>();
    	Group group;
    	ActionContext  context = ActionContext.getContext();
		Map session = context.getSession();
		System.out.println("setUserGroupsInSession debug 2.........");
		PreparedStatement ps;
		ResultSet rs;
    	try {
			//con = ConnMngt.getConnection();
    		con=lmDB.getDBConnection();
			String query = "select id, name from group_master";
			ps = con.prepareStatement(query);
			rs = ps.executeQuery();
			while(rs.next()){
				group = new Group();
				group.setGroupId(rs.getString(1));
				group.setGroupName(rs.getString(2));
				groups.add(group);
			}
			session.put("GROUPS", groups);
    	} catch (SQLException e) {
			e.printStackTrace();
		}
		System.out.println("setUserGroupsInSession debug 3s.........");
    }

    

} // End Class LoginService